from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from .ser import *

#老师注册接口
class TeacherM(APIView):
    def post(self,request):
        ser = TeacherSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        else:
            print(ser.errors)
            return Response({"code":20010})
#登录接口
class TeacherLogin(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        if username and password:
            #登录
            teacher = Teacher.objects.filter(username=username,password=password).first()
            if teacher:
                #返回200，用户id,用户名
                return Response({"code":200,'tid':teacher.id,'tname':teacher.username})
        else:
            return Response({"code":10010})


#添加展示学生
class StuM(APIView):
    def post(self,request):
        ser = TstuSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        else:
            print(ser.errors)
            return Response({"code":20010})
    def get(self,request):
        tid = request.GET.get('tid')
        stu = Tstu.objects.filter(teacher_id=tid).all()
        ser = TstuSer(stu,many=True)
        return Response({"code":200,'list':ser.data})

    def put(self, request):
        id = request.GET.get('id')
        Tstu.objects.filter(id=id).update(teacher_id='')
        return Response({"code": 200})

#添加展示学生
class StuN(APIView):
    def get(self,request):
        tid = request.GET.get('tid')
        if tid:
            stu = Tstu.objects.filter(teacher_id=tid).all()
        else:
            #没绑定的所有学生
            stu = Tstu.objects.filter(teacher_id__isnull=True).all()
        ser = TstuSer(stu,many=True)
        return Response({"code":200,'list':ser.data})
    def put(self,request):
        #学生id
        id = request.GET.get('id')
        tid = request.GET.get('tid')
        if tid:
            #绑定
            Tstu.objects.filter(id=id).update(teacher_id=tid)
        else:
            #解绑
            Tstu.objects.filter(id=id).update(teacher_id='')
        return Response({"code":200})

# Create your views here.
